# import py_compile
# py_compile.compile('F:/test.py')

# coding:utf-8
import datetime
import os, sys
import base64
from PIL import Image
from io import BytesIO
import time


class ProjectToHtml(object):
    def __init__(self, projectName, labelImgsPath, labelClasses, InputImagesSize, Epochs,
                 BatchSize, ValidateSplit,
                 LearningRate, IgnoreThresh, TrainTime, TrainTotalLoss, TrainValLoss, TrainEndEpochs, TrainDate,
                 TestImagesPath,
                 SaveOKImages, SaveNGImages, Score, IOU, TotalTestImages, NGImagesNum, NGImagesRate, TotalTestTime,
                 AverageTestTimePerImage,
                 TestDate):
        # savedir = cur_file_dir()  # 获取当前.py脚本文件的文件路径
        self.trainimgdir = labelImgsPath
        self.okImagesPath = SaveOKImages
        self.ngImagesPath = SaveNGImages
        self.labelClasses = labelClasses
        self.InputImagesSize = InputImagesSize
        self.Epochs = Epochs
        self.BatchSize = BatchSize
        self.ValidateSplit = ValidateSplit
        self.LearningRate = LearningRate
        self.IgnoreThresh = IgnoreThresh
        self.TrainTime = TrainTime
        self.TrainTotalLoss = TrainTotalLoss
        self.TrainValLoss = TrainValLoss
        self.TrainEndEpochs = TrainEndEpochs
        self.TrainDate = TrainDate
        self.TestImagesPath = TestImagesPath
        self.Score = Score
        self.IOU = IOU
        self.TotalTestImages = TotalTestImages
        self.NGImagesNum = NGImagesNum
        self.NGImagesRate = NGImagesRate
        self.TotalTestTime = TotalTestTime
        self.AverageTestTimePerImage = AverageTestTimePerImage
        self.TestDate = TestDate
        self.showImageInHTML(labelImgsPath, SaveOKImages, SaveNGImages, projectName)  # 浏览所有jpg,png,gif文件

    def showImageInHTML(self, trainimgdir, okImagesdir, ngImagesdir, projectName):
        self.ATime = 0
        self.ATime2 = 0
        trainimages = self.getAllFiles(trainimgdir)
        ngimages = self.getAllFiles(ngImagesdir)
        okimages = self.getAllFiles(okImagesdir)
        newfile = '%s\\%s-检测结果.html' % (trainimgdir, projectName)
        time1 = str(datetime.datetime.now()).split('.')[0]
        msgHeader1 = """
        <!DOCTYPE html>
        <html>
            <head>
            <meta charset="utf-8"> 
            <title>%s-检测报告</title>
            <h3 align="center">%s-检测报告<h1>
             <p class='attribute' algin="center" style="font-size: 14px;vertical-align:middle text-align:center">报告生成时间 : %s</p>
                <style type="text/css" media="screen">
                    body  { font-family: Microsoft YaHei,Tahoma,arial,helvetica,sans-serif;padding: 10px;}\n""" % (
            projectName, projectName, time1)
        msgHeader2 = """
        div.img {
            margin: 5px;
            border: 1px solid #ccc;
            float: left;
            width: 180px;
        }
        div.img:hover{
            border: 1px solid #777;
        }
        div.img img{
            width: 100%;
            height: auto;
        }
        div.desc{
            padding: 10px;
            text-align: center;
        }
        </style>
        </head>
        <body>\n"""
        Tabel = """
        <table id='result_table' border="1" class="table table-condensed table-bordered table-hover">
        <colgroup>
            <col align='left' />
            <col align='right' />
            <col align='right' />
        </colgroup>
        <tr>
            <th rowspan="2" width="100" id='header_row_Label' class="text-center success" style="font-weight: bold;font-size: 14px;background-color:yellow; vertical-align:middle">标注</th>
            <td width = "200" align="center" style="font-size: 14px;vertical-align:middle;background-color:gray">图片总数</td>
            <td width ="400" align="center" style="font-size: 14px;vertical-align:middle">%(LabelImagesNum)s</td>
        </tr>
        <tr>
            <td align="center" style="font-size: 14px;vertical-align:middle;background-color:light-gray">标注缺陷类别数</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(Labelclassescategories)s</td>
        </tr>
       <tr>
            <th rowspan=%(trainrows)s id='header_row_Label' class="text-center success" style="font-weight: bold;font-size: 14px;background-color:green;vertical-align:middle;">训练</th>
            <td rowspan= "1" align="center" style="font-size: 14px;vertical-align:middle;background-color:gray" >训练集</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(labelClasses)s</td>
        </tr>
        <tr>
            <td align="center" style="font-size: 14px;vertical-align:middle;background-color:light-gray">输入图片尺寸</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(InputImgSize)s</td>
        </tr>
        <tr>
            <td align="center" style="font-size: 14px;vertical-align:middle;background-color:gray">BatchSize</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(BatchSize)s</td>
        </tr>
        <tr>
            <td align="center" style="font-size: 14px;vertical-align:middle;background-color:light-gray">Valid Split</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(ValidSplit)s</td>
        </tr>
        <tr>
            <td align="center" style="font-size: 14px;vertical-align:middle;background-color:gray">Ignore Thresh</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(IgnoreThresh)s</td>
        </tr>
        <tr>
            <td align="center" style="font-size: 14px;vertical-align:middle;background-color:light-gray">Learning Rate</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(LearningRate)s</td>
        </tr>
        <tr>
            <td align="center" style="font-size: 14px;vertical-align:middle;background-color:gray">Training Time</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(TrainingTime)s</td>
        </tr> 
        <tr>
            <td align="center" style="font-size: 14px;vertical-align:middle;background-color:light-gray">Loss</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(Loss)s</td>
        </tr> 
        <tr>
            <td align="center" style="font-size: 14px;vertical-align:middle;background-color:gray">Validate Loss</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(ValidateLoss)s</td>
        </tr> 
        <tr>
            <th rowspan=%(inspectionrows)s id='header_row_Label' class="text-center success" style="font-weight: bold;font-size: 14px;background-color:red;vertical-align:middle;">检测</th>
            <td align="center" style="font-size: 14px;vertical-align:middle;background-color:light-gray">检测图片总数</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(TotalDetectImgs)s</td>
        </tr>
        <tr>
            <td align="center" style="font-size: 14px;vertical-align:middle;background-color:gray">NG图片总数</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(NGNum)s</td>
        </tr> 
        <tr>
            <td align="center" style="font-size: 14px;vertical-align:middle;background-color:light-gray">NG图片比重</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(NGNumRate)s</td>
        </tr> 
        <tr>
            <td align="center" style="font-size: 14px;vertical-align:middle;background-color:gray">总的检测时间</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(TotalDetecionTime)s</td>
        </tr> 
        <tr>
            <td align="center" style="font-size: 14px;vertical-align:middle;background-color:light-gray">平均每张图用时</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(averageTime)s</td>
        </tr> 
        <tr>
            <td align="center" style="font-size: 14px;vertical-align:middle;background-color:gray">Score</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(Score)s</td>
        </tr> 
        <tr>
            <td align="center" style="font-size: 14px;vertical-align:middle;background-color:light-gray">IOU</td>
            <td align="center" style="font-size: 14px;vertical-align:middle">%(IOU)s</td>
        </tr>

        %(table_tr)s
    </table>
    <p class='attribute' style="font-size: 18px;vertical-align:middle"><strong>训练集(%(trainImgsNum)s)</strong></p>"""

        total_str = str(datetime.datetime.now()).split('.')[0]
        table_tr0 = ''
        global i_
        i_ = 0
        global k_
        k_ = 0
        global j_
        j_ = 0.5
        global h_
        h_ = 0.5

        trainImgsNum = len(trainimages)
        okImagsNum = int(self.TotalTestImages) - int(self.NGImagesNum)
        Tabel = Tabel % dict(LabelImagesNum=trainImgsNum, Labelclassescategories=str(len(self.labelClasses)),
                             value=total_str,
                             table_tr=table_tr0,
                             InputImgSize=self.InputImagesSize,
                             BatchSize=self.BatchSize,
                             ValidSplit=self.ValidateSplit,
                             IgnoreThresh=self.IgnoreThresh,
                             LearningRate=self.LearningRate,
                             TrainingTime=self.TrainTime,
                             Loss=self.TrainTotalLoss,
                             ValidateLoss=self.TrainValLoss,
                             labelClasses = self.labelClasses,
                             trainrows=str(len(self.labelClasses) + 8),
                             TotalDetectImgs=self.TotalTestImages,
                             NGNum=self.NGImagesNum,
                             NGNumRate=self.NGImagesRate + '%',
                             TotalDetecionTime=self.TotalTestTime + 's',
                             averageTime=self.AverageTestTimePerImage + 's',
                             Score=self.Score,
                             IOU=self.IOU,
                             inspectionrows='7',
                            trainImgsNum=trainImgsNum, )

        with open(newfile, 'wb') as f:
            f.write(msgHeader1.encode("utf-8"))
            f.write(msgHeader2.encode("utf-8"))
            f.write(str(Tabel).encode("utf-8"))

            for i in range(trainImgsNum + 1):
                if i < trainImgsNum:
                    # f1 = open(trainimages[i], 'rb')
                    # self.compressImage(trainimages[i])
                    # bian_ma = base64.b64encode(f1.read())
                    begin = time.time()  #
                    bian_ma = self.compressImage(trainimages[i])
                    strbian_ma = str(bian_ma).split('\'')[1]
                    end = time.time()  #
                    Time = end - begin
                    self.ATime = Time + self.ATime
                    print('16点47')
                    print(self.ATime)
                    # f1.close()
                    pictureName = os.path.basename(trainimages[i])
                    begin1 = time.time()
                    message0 = """
                            <div class="responsive">
                              <div class="img">
                                <a target="_blank" href="%s">
                                  <img src="data:image/bmp;base64,%s" alt="图片文本描述" width="300" height="200">
                                </a>
                                <div class="desc" style="font-size: 14px;vertical-align:middle">%s</div>
                              </div>
                            </div>\n""" % (pictureName,strbian_ma, pictureName)
                    end1 = time.time()  #
                    Time2 = end1 - begin1
                    self.ATime2 = Time2 + self.ATime2
                    print('16点48')
                    print(self.ATime2)
                else:
                    message0 = """
                            <canvas id="myCanvas" width="2000" height="100"></canvas>
                            <script>
                            var c=document.getElementById("myCanvas");
                            var ctx=c.getContext("2d");
                            ctx.font="20px Arial";
                            ctx.fillText("检测集(NG：%s)",10,50);
                            </script>""" % str(self.NGImagesNum)


                f.write(message0.encode("utf-8"))
            for image in ngimages:
                # f2 = open(image, 'rb')
                i_ = i_ + 1
                k_ = k_ - 1
                j_ = j_ + 1
                h_ = h_ - 1
                bian_ma = self.compressImage(image)
                strbian_ma = str(bian_ma).split('\'')[1]
                # f2.close()
                pictureName = os.path.basename(image)
                #=====加入原图的路径
                image_yuan = r'C:\Users\SV00299057\Desktop\12312\12.jpg'##
                bian_ma_yuan = self.compressImage(image_yuan)
                strbian_ma_yuan = str(bian_ma_yuan).split('\'')[1]
                #=====
                # msg = """
                #        <div class="responsive">
                #          <div class="img">
                #            <a target="_blank" href="%s">
                #              <img src="data:image/bmp;base64,%s" alt="图片文本描述" width="300" height="200">
                #            </a>
                #            <div class="desc" style="font-size: 14px;vertical-align:middle">%s</div>
                #          </div>
                #        </div>\n""" % (pictureName,strbian_ma, pictureName)
                # f.write(msg.encode("utf-8"))


                msg = """
                    
                       <head>
                           <meta charset="UTF-8">
                       <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
                       </script>
                       <script>
                       $(document).ready(function(){
                       $("#%s").hover(function(){
                       $("#%s").css("visibility","visible");
                       },function(){
                       $("#%s").css("visibility","hidden");
                       });
                       });
                       </script>
                       </head> 
                                            
                       <div class="responsive">
                       <div class="img" id="%s" style="position:relative;background-color:white">
                             <a target="_blank" href="../../%s/NG/%s" id = "%s" >    
                             <img src="data:image/bmp;base64,%s" alt="图片文本描述" id = "%s" >
                             </a>
                             <button id="%s" type="button" style="position:absolute;top:0;right:0;visibility:hidden" onclick="handle()">显示原图</button>

                             <div class="desc" style="font-size: 14px;vertical-align:middle">%s</div>
                       <script>
                       function handle(){
                       var button = document.getElementById("%s");
                       var picts = document.getElementById("%s");
                       var pictss = document.getElementById("%s");
                       button.onclick = function(){
                       if(picts.getAttribute("src",2) == "data:image/bmp;base64,%s"){
                       picts.setAttribute("src","data:image/bmp;base64,%s");
                       pictss.setAttribute("href","%s");
                       }else{
                       picts.setAttribute("src","data:image/bmp;base64,%s");
                       pictss.setAttribute("href","../../%s/NG/%s");
                       };
                       }
                       }
                         handle();
                        </script>
                       </div>
                       </div>\n""" % (i_,k_,k_,i_,projectName,pictureName,h_,strbian_ma,j_,k_, pictureName,k_,j_,h_,strbian_ma,strbian_ma_yuan,pictureName,strbian_ma,projectName,pictureName)

                f.write(msg.encode("utf-8"))



                # msg = """
                #        <div class="responsive">
                #          <div class="img">
                #              <img id="%s" src="data:image/bmp;base64,%s" onclick="this.hidden = true; document.getElementById('%s').hidden = false" width="300" height="200">
                #              <img id="%s" src="data:image/bmp;base64,%s" hidden=true onclick="this.hidden = true; document.getElementById('%s').hidden = false" width="300" height="200">
                #              <div class="desc" style="font-size: 14px;vertical-align:middle">%s</div>
                #          </div>
                #        </div>\n""" % (i_,strbian_ma,k_,k_,strbian_ma_yuan,i_, pictureName)
                # f.write(msg.encode("utf-8"))


            messageok = """
                        <canvas id="myCanvas1" width="2000" height="100"></canvas>
                        <script>
                        var c=document.getElementById("myCanvas1");
                        var ctx=c.getContext("2d");
                        ctx.font="20px Arial";
                        ctx.fillText("检测集(OK：%s)",10,50);
                        </script>""" % str(okImagsNum)
            f.write(messageok.encode("utf-8"))
            for image in okimages:
                # f2 = open(image, 'rb')
                bian_ma = self.compressImage(image)
                strbian_ma = str(bian_ma).split('\'')[1]
                # f2.close()
                pictureName = os.path.basename(image)
                msg = """
                       <div class="responsive">
                         <div class="img">
                           <a target="_blank" href="%s">
                             <img src="data:image/bmp;base64,%s" alt="图片文本描述" width="300" height="200">
                           </a>
                           <div class="desc" style="font-size: 14px;vertical-align:middle">%s</div>
                         </div>
                       </div>\n""" % (pictureName,strbian_ma, pictureName)  #显示图像和名字
                f.write(msg.encode("utf-8"))






        print('success,images are wrapped up in %s' % newfile)

    def getAllFiles(self, directory):
        files = []
        for dirpath, dirnames, filenames in os.walk(directory):
            if filenames != []:
                for file in filenames:
                    files.append(dirpath + '\\' + file)
        files.sort(key=len)
        images = [f for f in files if f[f.rfind('.') + 1:] in ('jpg', 'png', 'gif', 'bmp', 'tif')]
        images = [item for item in images if os.path.getsize(item) > 5 * 1024]
        images = [directory + item[item.rfind('\\'):] for item in images]
        return images

    def compressImage(self, imgPath):
        sImg = Image.open(imgPath)
        dImg = sImg.resize((400, 400), Image.ANTIALIAS)
        return self.image_to_base64(dImg)

    def image_to_base64(self, img):
        # img = Image.open(image_path)
        output_buffer = BytesIO()
        img.save(output_buffer, format='png')
        byte_data = output_buffer.getvalue()
        base64_str = base64.b64encode(byte_data)
        return base64_str

    #
    # # 获取脚本文件的当前路径
    # def cur_file_dir():
    #     # 获取脚本路径
    #     path = sys.path[0]
    #     # 判断为脚本文件还是py2exe编译后的文件，如果是脚本文件，则返回的是脚本的目录，如果是py2exe编译后的文件，则返回的是编译后的文件路径
    #     if os.path.isdir(path):
    #         return path
    #     elif os.path.isfile(path):
    #         return os.path.dirname(path)


